package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioProperties p;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
//          判断桶是否存在
        boolean b = minioClient.bucketExists(BucketExistsArgs
                .builder()
                .bucket(p.getBucketName())
                .build());
//          创建桶
        if (!b) {
            minioClient.makeBucket(MakeBucketArgs
                    .builder()
                    .bucket(p.getBucketName())
                    .build());
        }
//          设置桶的访问权限(读)
        minioClient.setBucketPolicy(SetBucketPolicyArgs
                .builder()
                .bucket(p.getBucketName())
                .config(createBucketPolicyConfig(p.getBucketName()))
                .build());
//          设置文件本地名称(保护作用)
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
//          往桶(lease)里添加本地数据
        minioClient.putObject(PutObjectArgs
                .builder()
                .bucket(p.getBucketName())
//                     上传输入流(设置怎么上传)
                .stream(file.getInputStream(), file.getSize(), -1)
                .object(filename)
//                     设置文件的请求头
                .contentType(file.getContentType())
                .build());
//          返回访问路径
        return String.join("/", p.getEndpoint(), p.getBucketName(), filename);
    }

    //  设置桶的访问权限【%s是占位符号,与formattted方法里面的对象相对应】方法
    private String createBucketPolicyConfig(String bucketName) {

        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}

